package com.net.xpay.stat.scheduler;


import com.net.xpay.stat.task.UserAccountMoneyLeftStatDailyTask;
import com.net.common.util.MoneyUtil;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.helper.NoticeHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.common.model.search.UserSearchModel;
import com.net.xpay.core.domain.UserAccount;
import com.net.xpay.core.manager.UserAccountManager;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 2019/7/15 16:28

 * 用户服务费余额留存统计
 */
@Slf4j
@Component
public class UserAccountMoneyLeftScheduler {

    @Autowired
    private UserAccountMoneyLeftStatDailyTask userAccountMoneyLeftStatDailyTask;

    @Autowired
    private NoticeHelper noticeHelper;

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserShardManager userShardManager;

    @Autowired
    private UserAccountManager userAccountManager;

    /**
     * 初略统计用户服务费日留存
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void queryUserMoneyLeft() {
        List<Long> userIds = userManager.listIds(new UserSearchModel());
        Long balance = 0L;
        for (Long userId : userIds) {
            UserShard userShard = userShardManager.getById(userId);
            try {
                ShardUtil.setShardContext(userShard.getShardId());
                UserAccount userAccount = userAccountManager.getById(userId);
                balance += userAccount.getMoneyLeft();
            } finally {
                ShardUtil.cleanShardContext();
            }
        }
        log.info("queryUserMoneyLeft={}", MoneyUtil.convertCentToString(balance, 2));
    }

    /**
     * 精准统计用户服务费日留存
     */
    @Scheduled(cron = "0 5 0 * * ?")
    public void doUserAccountMoneyLeftStat() {
        try {
            long t1 = System.currentTimeMillis();
            log.info("start schedule doUserAccountMoneyLeftStat|now={}", LocalDateTime.now());
            userAccountMoneyLeftStatDailyTask.startDailyWork();
            long t2 = System.currentTimeMillis();
            log.info("end schedule doUserAccountMoneyLeftStat|now={}|cost={}", LocalDateTime.now(), t2 - t1);
            noticeHelper.sendSystemInfoNotice("用户日服务费留存统计生成完成，耗费时间：" + (t2 - t1), "text");
        } catch (Throwable e) {
            log.warn("doUserAccountMoneyLeftStat error", e);
            noticeHelper.sendSystemMonitorNotice("用户日服务费留存日统计失败|doUserDailyStat error", "text");
        }
    }









}
